package com.yjz.zpay.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.yjz.zpay.bean.OrderBean;
import com.yjz.zpay.bean.QrCodeBean;

import java.text.DecimalFormat;
import java.util.ArrayList;


public class DBManager {
    private SQLiteDatabase db;
    private DBHelper helper;

    public DBManager(Context context) {
        helper = new DBHelper(context);
        db = helper.getWritableDatabase();
    }

    public void addOrder(OrderBean ordereBean) {
        db.beginTransaction();// 开始事务
        try {
            db.execSQL("INSERT INTO payorder VALUES(null,?,?,?,?)", new Object[]{ordereBean.getMoney(), ordereBean.getNo(), ordereBean.getResult(), ordereBean.getPayuser()});
            db.setTransactionSuccessful();// 事务成功
        } finally {
            db.endTransaction();// 结束事务
        }
    }

    public boolean isExistAliBOrder(String no) {
        boolean isExist = false;
        String sql = "SELECT * FROM payorder WHERE tradeno='" + no + "'";
        Cursor c = ExecSQLForCursor(sql);
        if (c.getCount() > 0) {
            isExist = true;
        }
        c.close();
        return isExist;
    }

    public void updateOrder(String no, String result) {
        db.beginTransaction();// 开始事务
        try {
            db.execSQL("UPDATE payorder SET result=? WHERE tradeno=?", new Object[]{result, no});
            db.setTransactionSuccessful();// 事务成功
        } finally {
            db.endTransaction();// 结束事务
        }
    }

    public ArrayList<OrderBean> FindAllOrders() {
        String sql = "SELECT * FROM payorder where result <> 'success'";
        ArrayList<OrderBean> list = new ArrayList<OrderBean>();
        Cursor c = ExecSQLForCursor(sql);
        while (c.moveToNext()) {
            OrderBean info = new OrderBean();
            info.setMoney(c.getString(c.getColumnIndex("money")));
            info.setNo(c.getString(c.getColumnIndex("tradeno")));
            info.setResult(c.getString(c.getColumnIndex("result")));
            info.setPayuser(c.getString(c.getColumnIndex("payuser")));
            list.add(info);
        }
        c.close();
        return list;
    }

    /**
     * 执行SQL，返回一个游标
     *
     * @param sql
     * @return
     */
    private Cursor ExecSQLForCursor(String sql) {
        Cursor c = db.rawQuery(sql, null);
        return c;
    }
}
